package edu.ito.wx.authorize;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.ito.wx.util.Constant;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class OAuthGetOpenid {

    public String getOpenidByCode(String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ Constant.APP_ID+"&secret="+Constant.SECRET+"&code="+code+"&grant_type=authorization_code";
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        String openid = null;
        try {
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity);
            JSONObject obj = JSON.parseObject(responseContent);
            if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                if(obj.get("errcode")==null){
                    openid  = (String)obj.get("openid");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return openid;
    }
}
